﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using MM.DBUtility;

namespace MobileManager
{
    public partial class MruleManageEdit : System.Web.UI.Page
    {
        private MM.Model.T_Users userModel;
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Session["CurUser"] == null)
                {
                    Response.Redirect("Login.aspx");
                    return;
                }
                else
                {
                    userModel = (MM.Model.T_Users)Session["CurUser"];
                }
                if (!IsPostBack)
                {
                    lbProvince.Visible = false;
                    //BinDdlProvince(ref ddlProvince);
                    BindDdlODEP(ref ddlODEP);
                    BindDdlCustomer(ref ddlCustomer);
                    BindDdlChannel(ref ddlChannel);

                    string strID = string.Empty;
                    if (Request.QueryString["ID"] != null)
                        strID = Request.QueryString["ID"].ToString();
                    if (string.IsNullOrEmpty(strID))
                    {
                        //BindDdlArea(ref ddlArea, ddlProvince.SelectedValue);
                        //ddlArea.Items.Insert(0, new ListItem("全部", "-1"));
                        btnSave.Text = "添 加";
                    }
                    else
                    {
                        ViewState["ID"] = strID;
                        btnSave.Text = "保 存";
                        DataSet ds = DbHelperSql.Query(string.Format("select * from T_Rules WITH(NOLOCK) where ID={0}", strID));
                        if (ds != null && ds.Tables.Count > 0)
                        {
                            lbProvince.Visible = true;
                            lbProvince.Text = MM.DBUtility.BLSqlData.GetNameByProvinceID(ds.Tables[0].Rows[0]["ProvinceID"].ToString());

                            ddlODEP.SelectedValue = ds.Tables[0].Rows[0]["ONO"].ToString();
                            ddlCustomer.SelectedValue = ds.Tables[0].Rows[0]["CNO"].ToString();
                            ddlChannel.SelectedValue = ds.Tables[0].Rows[0]["ChannelNO"].ToString();
                            ddlStatus.SelectedValue = ds.Tables[0].Rows[0]["Status"].ToString();

                            txtCount.Text = ds.Tables[0].Rows[0]["SendCount"].ToString();
                            inputDate.Value = ds.Tables[0].Rows[0]["NextTime"].ToString();
                            txtTimeInterval.Text = ds.Tables[0].Rows[0]["TimeInterval"].ToString();

                            txtProvince.Visible = false;
                            ddlODEP.Enabled = false;
                            ddlCustomer.Enabled = false;
                        }
                        else
                        {
                            btnSave.Visible = false;
                        }
                    }
                    if (ddlODEP.Items.Count <= 0 || ddlCustomer.Items.Count <= 0 || ddlODEP.Items.Count <= 0)
                        btnSave.Visible = false;
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #region DDL Bind
        private void BinDdlProvince(ref DropDownList ddl)
        {
            ddl.DataSource = BLSqlData.AllProvince;
            ddl.DataValueField = "ProvinceID";
            ddl.DataTextField = "ProvinceName";
            ddl.DataBind();
        }
        //private void BindDdlArea(ref DropDownList ddl, string strProvinceID)
        //{
        //    ddl.DataSource = DbHelperSql.Query(string.Format("SELECT AreaNO,AreaNO+'-'+ CityName as Name FROM T_Area WHERE ProvinceID={0}", strProvinceID)).Tables[0];
        //    ddl.DataValueField = "AreaNO";
        //    ddl.DataTextField = "Name";
        //    ddl.DataBind();
        //}
        private void BindDdlODEP(ref DropDownList ddl)
        {
            ddl.DataSource = DbHelperSql.Query("SELECT ONO,ONO+'-'+ OName as Name FROM T_ODEP WITH(NOLOCK) ").Tables[0];
            ddl.DataValueField = "ONO";
            ddl.DataTextField = "Name";
            ddl.DataBind();
        }
        private void BindDdlCustomer(ref DropDownList ddl)
        {
            string strSQL = "SELECT CNO,CNO+'-'+ CName as Name FROM T_Customers WITH(NOLOCK) ";

            if (!string.IsNullOrEmpty(userModel.CustomerNO))
                strSQL += string.Format(" WHERE CNO IN ({0})", BLSqlData.GetInSQL(userModel.CustomerNO));

            ddl.DataSource = DbHelperSql.Query(strSQL).Tables[0];
            ddl.DataValueField = "CNO";
            ddl.DataTextField = "Name";
            ddl.DataBind();
        }
        private void BindDdlChannel(ref DropDownList ddl)
        {
            ddl.DataSource = DbHelperSql.Query("SELECT ChannelNO,ChannelNO+'-'+ ChannelNumber+'-'+ChannelOrder as Name FROM T_Channel WITH(NOLOCK)  order by ChannelNO").Tables[0];
            ddl.DataValueField = "ChannelNO";
            ddl.DataTextField = "Name";
            ddl.DataBind();
        }
        #endregion

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtCount.Text.Trim()))
                {
                    MM.Common.Common.PageStartAlert(this.Page, "发送条数不能为空！");
                    return;
                }
                if (string.IsNullOrEmpty(inputDate.Value.Trim()))
                {
                    MM.Common.Common.PageStartAlert(this.Page, "下次联网时间不能为空！");
                    return;
                }
                if (ViewState["ID"] != null && !string.IsNullOrEmpty(ViewState["ID"].ToString()))
                {
                    MM.DBUtility.DbHelperSql.ExecuteSql(string.Format("UPDATE T_Rules SET ChannelNO='{0}',SendCount={1},NextTime='{2}',TimeInterval='{3}',Status='{4}' WHERE ID={5}", ddlChannel.SelectedValue, txtCount.Text.Trim(), inputDate.Value.Trim(), txtTimeInterval.Text.Trim(), ddlStatus.SelectedValue, ViewState["ID"].ToString()));
                    MM.DBUtility.BLSqlData.InsertLogs(userModel.UserID, string.Format("更新了规则信息：ID={0}。", ViewState["ID"].ToString()), "规则管理");
                    MM.Common.Common.PageAlertAndRedirect(this.Page, "更新成功！", "MruleManage.aspx");
                }
                else
                {
                    string strProvinceID = MM.DBUtility.BLSqlData.GetProvinceIDbyQuickName(txtProvince.TextValue);
                    if (string.IsNullOrEmpty(strProvinceID))
                    {
                        MM.Common.Common.PageStartAlert(this.Page, "必须选择省份，或省份选择错误！");
                        return;
                    }

                    if (BLSqlData.ExistRules(strProvinceID, ddlODEP.SelectedValue, ddlCustomer.SelectedValue))
                    {
                        MM.Common.Common.PageStartAlert(this.Page, "省份,运营商,客户编号对应的规则已经存在！");
                        return;
                    }

                    MM.DBUtility.DbHelperSql.ExecuteSql(string.Format("insert into T_Rules(ProvinceID,ONO,CNO,ChannelNO,SendCount,NextTime,Status,TimeInterval,flag) values({0},'{1}','{2}','{3}',{4},'{5}','{6}','{7}','0')", strProvinceID, ddlODEP.SelectedValue, ddlCustomer.SelectedValue, ddlChannel.SelectedValue, txtCount.Text.Trim(), inputDate.Value.Trim(), ddlStatus.SelectedValue, txtTimeInterval.Text.Trim()));
                    MM.DBUtility.BLSqlData.InsertLogs(userModel.UserID, string.Format("添加了规则信息：ProvinceID={0},ONO={1},CNO={2}。", strProvinceID, ddlODEP.SelectedValue, ddlCustomer.SelectedValue), "规则管理");

                    MM.Common.Common.PageAlertAndRedirect(this.Page, "添加成功！", "MruleManage.aspx");
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        //protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        ddlArea.Items.Clear();
        //        BindDdlArea(ref ddlArea, ddlProvince.SelectedValue);
        //        ddlArea.Items.Insert(0, new ListItem("全部", "-1"));
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //}
    }
}
